//
//  SubscibeViewController.m
//  安好
//
//  Created by qinlongqing on 14/12/9.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "SubscibeViewController.h"
#import "AppConfig.h"
#import "SystemSubscibeCell.h"
#import "SubscibeModel.h"
#import "CLDataBaseController.h"
#import "SubscibeDetailViewController.h"
#import "EditSubscibeViewController.h"
#import "MyPoperView.h"
#import "SystemMessageCenter.h"


@interface SubscibeViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    UITableView *mTableView;
    
    NSInteger page;
    NSInteger pageSize;
    
    NSString *action;
    NSInteger cid;
    NSString *catName;
    
    UILabel *_hintLabel;
    
    NSMutableArray *subscibeArrays;
    
    UIButton *popButton;
    
    NSMutableArray *allSystemSubscibe;
    NSMutableArray *allCustomSubscibe;
    
    MyPoperView *popView;
    NSMutableArray *allSystemSubscibeNameArray;
    NSMutableArray *allCustomSubscibeNameArray;
    
    BOOL shouldLoadFromNetwork;
}
@end

@implementation SubscibeViewController

- (void)viewDidAppear:(BOOL)animated{
    [self loadSubscibeData];
    
    shouldLoadFromNetwork = YES;
    
    if (!popButton) {
        popButton = [[UIButton alloc]initWithFrame:CGRectMake(kScreenWidth/2 - 50 + 8, 7, 100, 30)];
    }
    popButton.imageEdgeInsets = UIEdgeInsetsMake(0, 70, 0, 0);
    [popButton addTarget:self action:@selector(doShowAllSubscibe:) forControlEvents:UIControlEventTouchUpInside];
    [popButton setImage:[UIImage imageNamed:@"subscibe_down"] forState:UIControlStateNormal];
    popButton.backgroundColor = [UIColor clearColor];
//    popButton.alpha = 0.7;
    popButton.userInteractionEnabled = YES;
    [self.navigationController.navigationBar addSubview:popButton];
    
    [super viewDidAppear:animated];
}

- (void)doShowAllSubscibe:(UIButton *)sender{
    popButton.userInteractionEnabled = NO;
    
    if (shouldLoadFromNetwork == YES) {
        NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion,@"people":@"0"};
        [[AFHTTPRequestOperationManager manager] POST:[NSString stringWithFormat:@"%@%@",kBaseURL,kGetAllSubscibeURL] parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSNumber * statusNum = [responseObject objectForKey:@"status"];
            NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
            NSString * statusString = [numberFormatter stringFromNumber:statusNum];
            if ([statusString isEqualToString:@"0"]) {
                popButton.userInteractionEnabled = YES;
            }
            else{
                NSArray *allSystemSubscibeTemp = [[responseObject valueForKey:@"data"] valueForKey:@"sys"];
                [allSystemSubscibe removeAllObjects];
                [allSystemSubscibeNameArray removeAllObjects];
                for (NSInteger i=0; i<allSystemSubscibeTemp.count; i++) {
                    if ([[[allSystemSubscibeTemp objectAtIndex:i] valueForKey:@"status"] integerValue] == 1) {
                        [allSystemSubscibe addObject:[allSystemSubscibeTemp objectAtIndex:i]];
                        [allSystemSubscibeNameArray addObject:[[allSystemSubscibeTemp objectAtIndex:i] valueForKey:@"catname"]];
                    }
                }
                
                allCustomSubscibe = [[responseObject valueForKey:@"data"] valueForKey:@"my"];
                [allCustomSubscibeNameArray removeAllObjects];
                for (NSInteger i=0; i<allCustomSubscibe.count; i++) {
                    [allCustomSubscibeNameArray addObject:[[allCustomSubscibe objectAtIndex:i] valueForKey:@"catname"]];
                }

                shouldLoadFromNetwork = NO;
                popButton.userInteractionEnabled = YES;
                [self createAndShowPoperView];
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            popButton.userInteractionEnabled = YES;
        }];
    }
    else{
        popButton.userInteractionEnabled = YES;
        [self createAndShowPoperView];
    }
}

//显示popview
- (void)createAndShowPoperView{
    CGPoint point = CGPointMake(popButton.frame.origin.x + popButton.frame.size.width/2 - 10, 64);
    
    NSMutableArray *allArray = [NSMutableArray arrayWithObjects:[NSArray arrayWithObjects:@"查看全部", nil], nil];
    if (allSystemSubscibeNameArray.count > 0) {
        [allArray insertObject:allSystemSubscibeNameArray atIndex:0];
    }
    if (allCustomSubscibeNameArray.count > 0) {
        [allArray insertObject:allCustomSubscibeNameArray atIndex:0];
    }
    popView = [[MyPoperView alloc]initWithPoint:point titles:allArray images:nil];
    __block SubscibeViewController *blockSelf = self;
    popView.selectRowAtIndex = ^(NSIndexPath *indexPath){
        [blockSelf->subscibeArrays removeAllObjects];
        blockSelf->page = 1;
        
        if (blockSelf->allCustomSubscibe.count > 0) {
            if (indexPath.section == 0) {//自定义订阅
                blockSelf->action = @"my";
                blockSelf->cid = [[[blockSelf->allCustomSubscibe objectAtIndex:indexPath.row] valueForKey:@"cid"] integerValue];
                blockSelf->catName = [[blockSelf->allCustomSubscibe objectAtIndex:indexPath.row] valueForKey:@"catname"];
                [blockSelf loadSubscibeData];
            }
            else if (indexPath.section == 1){//系统订阅
                blockSelf->action = @"sys";
                blockSelf->cid = [[[blockSelf->allSystemSubscibe objectAtIndex:indexPath.row] valueForKey:@"cid"] integerValue];
                blockSelf->catName = [[blockSelf->allSystemSubscibe objectAtIndex:indexPath.row] valueForKey:@"catname"];
                [blockSelf loadSubscibeData];
            }
            else{//查看全部
                blockSelf->action = nil;
                blockSelf->cid = 0;
                blockSelf->catName = nil;
                [blockSelf loadSubscibeData];
            }
        }
        else if (blockSelf->allSystemSubscibe.count > 0){
            if (indexPath.section == 0) {
                blockSelf->action = @"sys";
                blockSelf->cid = [[[blockSelf->allSystemSubscibe objectAtIndex:indexPath.row] valueForKey:@"cid"] integerValue];
                blockSelf->catName = [[blockSelf->allSystemSubscibe objectAtIndex:indexPath.row] valueForKey:@"catname"];
                [blockSelf loadSubscibeData];
            }
            else{//查看全部
                blockSelf->action = nil;
                blockSelf->cid = 0;
                blockSelf->catName = nil;
                [blockSelf loadSubscibeData];
            }
        }
        else{
            blockSelf->action = nil;
            blockSelf->cid = 0;
            blockSelf->catName = nil;
            [blockSelf loadSubscibeData];
        }
    };
    [popView show];
}

- (void)viewWillDisappear:(BOOL)animated{
    [subscibeArrays removeAllObjects];
    page = 1;
    action = nil;
    cid = 0;
    catName = nil;

    
    [popView dismiss];

    [popButton removeFromSuperview];
    
    [super viewWillDisappear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    //设置7天将本地文件夹删除一次
    [self accordingToInterval:7*24*60*60 withUserDateForKey:@"SubscriptionDate" JudgeRemoveFileName:@"SubscriptionImg"];
    
    page = 1;
    pageSize = 10;
    action = nil;
    cid = 0;
    catName = nil;
    
    self.view.backgroundColor = UIColorFromRGB(0xf2f2f2);
    
    subscibeArrays = [[NSMutableArray alloc]init];

    [self makeNavBar];
    
    [self createTableView];
    
    allSystemSubscibe = [[NSMutableArray alloc]init];
    allCustomSubscibe = [[NSMutableArray alloc]init];
    
    allSystemSubscibeNameArray = [[NSMutableArray alloc]init];
    allCustomSubscibeNameArray = [[NSMutableArray alloc]init];
    
    
    
    
}

/**
 *  根据保存在NSUserDefaults中的时间和现在的时间的间隔，决定是否删除本地的文件夹
 *
 *  @param interval    规定的时间间隔
 *  @param userDateKey 在NSUserDefault中保存原来日期的key，
 *  @param floderName  在本地沙盒目录下FileManager中的文件夹的名字
 */
-(void)accordingToInterval:(NSTimeInterval)interval withUserDateForKey:(NSString*)userDateKey JudgeRemoveFileName:(NSString*)floderName{
    
    NSUserDefaults * timeUser = [NSUserDefaults standardUserDefaults];
    NSDate * oldTime = [timeUser objectForKey:userDateKey];
    NSDate * nowDate = [NSDate date];
    if (oldTime == nil) {
        [timeUser setObject:nowDate forKey:userDateKey];
        [timeUser synchronize];
    }else{
        NSTimeInterval Timeinterval = [nowDate timeIntervalSinceDate:oldTime];
        if (Timeinterval >= interval) {
            //删除
            //本地沙盒文件路径
            NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
            //保存图片的文件夹
            NSString *imagesPath = [documentPath stringByAppendingString:[NSString stringWithFormat:@"/%@/",floderName]];
            if ([[NSFileManager defaultManager] fileExistsAtPath:imagesPath]) {
                [[NSFileManager defaultManager] removeItemAtPath:imagesPath error:nil];
            }
            [timeUser setObject:nowDate forKey:userDateKey];
        }
    }
    
}




-(void)makeNavBar{
    self.navigationItem.title = @"我的订阅";
    UIBarButtonItem *backBtnImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(backBtnclicked)];
    backBtnImg.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = backBtnImg;
    
    
    UIButton *changeSubscibeBTN = [[UIButton alloc]initWithFrame:CGRectMake(240, 24, 80, 35)];
    [changeSubscibeBTN setTitle:@"修改订阅" forState:UIControlStateNormal];
    changeSubscibeBTN.titleLabel.font = [UIFont systemFontOfSize:15];
    [changeSubscibeBTN setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [changeSubscibeBTN addTarget:self action:@selector(doToChangeSubscibe) forControlEvents:UIControlEventTouchUpInside];
    [changeSubscibeBTN sizeToFit];
    UIBarButtonItem *changeSubscibeButtonItem = [[UIBarButtonItem alloc]initWithCustomView:changeSubscibeBTN];
    self.navigationItem.rightBarButtonItem = changeSubscibeButtonItem;
}

- (void)backBtnclicked{
    [popButton removeFromSuperview];

    [self.navigationController popViewControllerAnimated:YES];
}

- (void)doToChangeSubscibe{
    EditSubscibeViewController *edit = [[EditSubscibeViewController alloc]initWithNibName:@"EditSubscibeViewController" bundle:nil];
    [self.navigationController pushViewController:edit animated:YES];
}

- (void)createTableView{
    mTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64) style:UITableViewStyleGrouped];
//    mTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    mTableView.separatorColor = COLOR(221, 221, 221, 1);
    mTableView.backgroundColor = [UIColor clearColor];
    mTableView.delegate = self;
    mTableView.dataSource = self;
    [mTableView addHeaderWithTarget:self action:@selector(refreshSubscibeData)];
    [mTableView addFooterWithTarget:self action:@selector(loadSubscibeData)];
    [self.view addSubview:mTableView];
    
    _hintLabel = [[UILabel alloc] init];
    [mTableView.superview addSubview:_hintLabel];
    _hintLabel.text = @"没有更多了";
    _hintLabel.textAlignment=NSTextAlignmentCenter;
    _hintLabel.font = [UIFont systemFontOfSize:10];
    _hintLabel.textColor = [UIColor whiteColor];
    _hintLabel.backgroundColor = [UIColor blackColor];
    _hintLabel.layer.cornerRadius = 5;
    _hintLabel.layer.masksToBounds = YES;
    _hintLabel.alpha = 0;
    _hintLabel.frame = CGRectMake((mTableView.frame.size.width - 60) / 2, mTableView.frame.size.height + mTableView.frame.origin.y - 40, 60, 30);
}

- (void)refreshSubscibeData{
    page = 1;
    [self loadSubscibeData];
}

- (void)loadSubscibeData{
    if (page == 1) {
        [self showActionView];
    }
    
    NSDictionary *parameters;
    if ([action isEqualToString:@"my"]) {
        parameters = @{@"platform": kPlatform,@"version":kVersion,@"page":[NSString stringWithFormat:@"%ld",page],@"pagesize":[NSString stringWithFormat:@"%ld",pageSize],@"people":@"0",@"action":action,@"catname":catName,@"cid":[NSString stringWithFormat:@"%ld",cid]};
    }
    else if ([action isEqualToString:@"sys"]){
        parameters = @{@"platform": kPlatform,@"version":kVersion,@"page":[NSString stringWithFormat:@"%ld",page],@"pagesize":[NSString stringWithFormat:@"%ld",pageSize],@"people":@"0",@"action":action,@"cid":[NSString stringWithFormat:@"%ld",cid]};
    }
    else{
        parameters = @{@"platform": kPlatform,@"version":kVersion,@"page":[NSString stringWithFormat:@"%ld",page],@"pagesize":[NSString stringWithFormat:@"%ld",pageSize],@"people":@"0"};
    }
    [[AFHTTPRequestOperationManager manager] POST:[NSString stringWithFormat:@"%@%@",kBaseURL,kGetSubscibeListURL] parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [mTableView footerEndRefreshing];
        [mTableView headerEndRefreshing];
        
        if (page == 1) {
            [self hiddenActionView];
            [subscibeArrays removeAllObjects];
        }
        
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
            [self shouLabel:@"暂无订阅消息"];
            [subscibeArrays removeAllObjects];
            [mTableView reloadData];
        }
        else{
            NSInteger numbers = subscibeArrays.count;
            if ([[responseObject objectForKey:@"data"] count] != 0) {
                NSArray *allSubscibe = [responseObject objectForKey:@"data"];
                for (NSInteger i=0; i<allSubscibe.count; i++) {
                    SubscibeModel *model = [[SubscibeModel alloc]initWithDict:[allSubscibe objectAtIndex:i]];
                    [subscibeArrays addObject:model];
                }
                //pic = http://image.niruoanhao.com/news/2015/01/09/728.jpg  这里如果图片更新只会变化，那么这个图片地址的中显示年月日的地方会显示变化后的日期
                
                page +=1;
                
                [mTableView reloadData];
            }
            if (numbers == subscibeArrays.count) {
                [UIView animateWithDuration:0.4f animations:^{
                    _hintLabel.alpha = 0.6;
                } completion:^(BOOL finished) {
                    if (finished) {
                        [UIView animateWithDuration:0.5 animations:^{
                            _hintLabel.alpha = 0;
                        }];
                    }
                }];
            }
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
       
        [self hiddenActionView];
    }];
}

#pragma UITableViewDelegate相关
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (kScreenWidth == 414) {
        return 108;
    }
    return 90;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return subscibeArrays.count;
}
//得到图片的大小
-(UIImage *)imageFromImage:(UIImage *)image inRect:(CGRect)rect {
    CGImageRef sourceImageRef = [image CGImage];
    CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, rect);
    UIImage *newImage = [UIImage imageWithCGImage:newImageRef];
    return newImage;
}
/**
 *  把字符串中的某个字符(串)替换，的到新的字符串
 *
 *  @param originalString 需要修改的字符串
 *  @param placeStr       替换成新的字符
 *  @param cutString      原先的字符串，需要被替换的字符串
 *
 *  @return 返回新的字符串
 */
-(NSString*)ModificationTheString:(NSString *)originalString withTheCharString:(NSString*)placeStr replaceTheNeedCutString:(NSString*)cutString
{
    
    NSMutableString * subPicName = [NSMutableString stringWithCapacity:0];
    NSRange flagRange = [originalString rangeOfString:cutString];
    if (flagRange.location != NSNotFound) {
        NSArray * subArray = [[NSArray alloc] initWithArray:[originalString componentsSeparatedByString:cutString]];
        for (int i = 0; i < subArray.count; i++) {
            [subPicName appendString:subArray[i]];
            if (i!= subArray.count-1) {
                [subPicName appendString:placeStr];
            }
        }
    }else{
        [subPicName appendString:originalString];
    }
    
    return subPicName;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"systemSubscibeCell";
    SystemSubscibeCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        if (kScreenWidth == 414) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"SystemSubscibeCell" owner:self options:nil] lastObject];
        }
        else{
            cell = [[[NSBundle mainBundle] loadNibNamed:@"SystemSubscibeCell" owner:self options:nil] firstObject];
        }
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.userPhotoImageView.layer.cornerRadius = 3;
    cell.userPhotoImageView.clipsToBounds = YES;
    SubscibeModel *model = [subscibeArrays objectAtIndex:indexPath.row];
    
    //本地沙盒文件路径
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    //创建一个文件夹保存订阅的图片
    NSString *imagesPath = [documentPath stringByAppendingString:[NSString stringWithFormat:@"/SubscriptionImg/%@",model.cidForSubscibe]];
    if (![[NSFileManager defaultManager] fileExistsAtPath:imagesPath]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:imagesPath withIntermediateDirectories:YES attributes:nil error:nil];
        //在创建文件夹的时候就把此时的时间保存下来
        NSUserDefaults * timeUser = [NSUserDefaults standardUserDefaults];
        //先判断是否已经有了保存文件的时间
        NSDate * oldTime = [timeUser objectForKey:@"SubscriptionDate"];
        NSDate * nowDate = [NSDate date];
        //如果没有那么就把此时的时间保存下来
        if (oldTime == nil) {
            [timeUser setObject:nowDate forKey:@"SubscriptionDate"];
            [timeUser synchronize];
        }
    }
    //把图片的名字从本地取出
    NSUserDefaults * picUser = [NSUserDefaults standardUserDefaults];
    NSString * picUrl = [picUser objectForKey:[NSString stringWithFormat:@"%@%@",model.cidForSubscibe,model.nidForSubscibe]];
    BOOL picChange = NO;
    if (picUrl != nil && ![picUrl isEqualToString:model.picForSubscibe]) {
        picChange = YES;
    }
    //在这个文件夹下给图片取一个名字
    NSString * subImgPath = [imagesPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@.jpg",model.cidForSubscibe,model.nidForSubscibe]];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:subImgPath]) {
        if (picChange) {
            [fileManager removeItemAtPath:subImgPath error:nil];
        }
        [picUser setObject:model.picForSubscibe forKey:[NSString stringWithFormat:@"%@%@",model.cidForSubscibe,model.nidForSubscibe]];
        [picUser synchronize];
        [cell.userPhotoImageView setImageWithURL:[NSURL URLWithString:model.picForSubscibe] placeholderImage:[UIImage imageNamed:@"subscibe_default"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
            CGRect range = CGRectMake(0, 0,image.size.height, image.size.height);
            UIImage * downImg = [self imageFromImage:image inRect:range];
            //把这个图片按这个图片的名字保存下来
            [UIImageJPEGRepresentation(downImg, 0.5) writeToFile:subImgPath atomically:YES];
        }];
    
    }else{
        
        UIImage * localImg = [UIImage imageWithContentsOfFile:subImgPath];
        [cell.userPhotoImageView setImage:localImg];
    }
    cell.subscibeTitleLabel.text = model.titleForSubscibe;
    cell.subscibeDetailLabel.text = model.catnameForSubscibe;
    cell.subscibeDateLabel.text = model.datelineForSubscibe;
    if ([[CLDataBaseController instance] getIsReadedSubscibeWithNid:model.nidForSubscibe]) {
        cell.isNewImageView.hidden = YES;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    SystemSubscibeCell *cell = (SystemSubscibeCell *)[tableView cellForRowAtIndexPath:indexPath];
    SubscibeModel *model = [subscibeArrays objectAtIndex:indexPath.row];

    if (cell.isNewImageView.hidden == NO) {
        cell.isNewImageView.hidden = YES;
        
        [[CLDataBaseController instance] insertReadedSubscibeWithNid:model.nidForSubscibe];
    }
    
    NSString *imagesPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingString:[NSString stringWithFormat:@"/SubscriptionImg/%@",model.cidForSubscibe]];
    NSString * subImgPath = [imagesPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@.jpg",model.cidForSubscibe,model.nidForSubscibe]];
    SubscibeDetailViewController *detail = [[SubscibeDetailViewController alloc]init];
    detail.subscibeModel = model;
    detail.subscibeViewController = self;
    detail.localPathForImage = subImgPath;
    [self.navigationController pushViewController:detail animated:YES];
}

- (void)updateIsCollectionWithNid:(NSString *)nid andIsCollection:(NSInteger)isCollection{
    for (NSInteger i=0; i<subscibeArrays.count; i++) {
        SubscibeModel *model = [subscibeArrays objectAtIndex:i];
        if ([model.nidForSubscibe integerValue] == [nid integerValue]) {
            model.iscollectionForSubscibe = isCollection;
            break;
        }
    }
    [super updateIsCollectionWithNid:nid andIsCollection:isCollection];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
